<?php

namespace app\models;

use app\traits\ModelTrait;
use Phalcon\Mvc\Model;

/**
 * Class Blog
 * @package app\models
 * @property integer id
 * @property string title
 * @property string content
 * @property integer author
 * @property integer created_at
 * @property integer updated_at
 */
class Blog extends Model
{
    use ModelTrait;

    public $title;

    public $content;

    public $tags;

    public $updated_at;

    public $created_at;

    public $author;

    protected $_tagsModel;

    const TABLE = 'blog';

    public function getSource()
    {
        return self::TABLE;
    }

    public function beforeValidation()
    {
        if (empty($this->title)) {
            self::$error = '标题不能为空';
            return false;
        }
        if (strlen($this->title) > 255) {
            self::$error = '标题长度限制255个字节';
            return false;
        }
        if (empty($this->content)) {
            self::$error = '内容不能为空';
            return false;
        }
        if (empty($this->tags)) {
            self::$error = '标签不能为空';
            return false;
        }
        if (count($this->tags) > 5) {
            self::$error = '最多5个标签';
            return false;
        }
        return true;
    }

    /**
     * 更新关联的标签
     * 先查找出，当前已关联的标签
     * 对比，没有的插入
     */
    public function afterSave()
    {
        $tagsModel = $this->getTagsModel();
        $this->checkTags($tagsModel, $this->tags);
    }

    public function beforeCreate()
    {
        $this->updated_at = $this->created_at = time();
        $user = $this->getDI()->getShared('session')->get('user');
        $this->author = $user['id'];
    }

    public static function getShowContent($content)
    {
        $content = htmlspecialchars($content);
        return mb_substr($content, 0 ,50);
    }

    public function getTagsModel()
    {
        if ($this->_tagsModel) {
            return $this->_tagsModel;
        }
        $this->_tagsModel = [];
        $query = 'select tag.* from ' . Tag::className() . ' as tag left join ' . TagToBlog::className() . ' as tag_to_blog ' .
         ' on tag_to_blog.tag_id=tag.id left join ' . self::className() . ' as blog on tag_to_blog.blog_id=' . $this->id . ' limit 5';
        $this->getDI()->get('logger')->info($query);
        $result = $this->getModelsManager()->executeQuery($query);
        foreach ($result as $value) {
            $this->_tagsModel[] = $value;
        }
        return $this->_tagsModel;
    }

    public function getTgsArray()
    {
        $tagsModel = $this->getTagsModel();
        $tags = [];
        foreach ($tagsModel as $tagModel) {
            $tags[] = $tagModel->title;
        }
        return $tags;
    }

    public function checkTags($tagsModel, $tags)
    {
        /**
         * 找出需要插入数据库的tag
         */
        $insertTag = [];
        foreach ($tags as $tag) {
            foreach ($tagsModel as $model) {
                if ($model->title == $tag) {
                    continue ;
                }
            }
            $insertTag[] = $tag;
        }
        if (empty($insertTag)) {
            return true;
        }
        //高级sql语法不会，老老实实的 先判断tag是否存在，不存在则插入数据库
        $tagIds = [];
        foreach ($insertTag as $tag) {
            $result = Tag::findFirst([
                'conditions' => 'title=?1',
                'bind' => [
                    1 => $tag
                ],
            ]);
            if (!$result) {
                $tagModel = new Tag();
                $tagModel->title = $tag;
                $tagModel->save();
                $result = $tagModel;
            }
            $exist = TagToBlog::findFirst([
                'conditions' => 'tag_id=' . $result->id . ' and blog_id=' . $this->id,
            ]);
            if (!$exist) {
                $exist = new TagToBlog();
                $exist->tag_id = $result->id;
                $exist->blog_id = $this->id;
                $exist->save();
            }
        }
        return true;
    }
}